<template>
  <div class="container">
    <div class="container-content">
      <vab-query-form>
        <vab-query-form-top-panel>
          <el-form
            :inline="true"
            label-width="80px"
            :model="tableOptions.queryForm"
          >
            <el-form-item label="用户名称">
              <el-input
                v-model="tableOptions.queryForm.userName"
                placeholder="用户名称"
              />
            </el-form-item>
            <el-form-item label="用户账号">
              <el-input
                v-model="tableOptions.queryForm.userCode"
                placeholder="用户账号"
              />
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <easy-dict-select
                ref="statusRef"
                :default-value="tableOptions.queryForm.status"
                dict-code="1000"
                @change="handleStatusChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="refresh-left"
                type="warning"
                @click="handleResetQuery"
              >
                重置
              </el-button>
              <el-button icon="Search" type="primary" @click="queryTableData">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-top-panel>
        <vab-query-form-left-panel :span="24">
          <el-button
            v-auth="['sysuser/xz']"
            icon="circle-plus"
            type="primary"
            @click="handleAdd"
          >
            添加
          </el-button>
          <el-button
            v-auth="['sysuser/sc']"
            icon="remove"
            type="danger"
            @click="handleDelete"
          >
            批量删除
          </el-button>
          <el-button
            v-auth="['sysuser/sd']"
            icon="lock"
            type="primary"
            @click="handleLock(row)"
          >
            锁定
          </el-button>
          <el-button
            v-auth="['sysuser/jcsd']"
            icon="unlock"
            type="danger"
            @click="handleUnLock(row)"
          >
            解除锁定
          </el-button>
        </vab-query-form-left-panel>
      </vab-query-form>
      <el-table
        ref="tableRef"
        v-loading="tableOptions.loading"
        border
        :data="tableOptions.dataList"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        :height="tableOptions.height"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="handleSortChange"
      >
        <el-table-column
          align="center"
          show-overflow-tooltip
          type="selection"
          width="50"
        />
        <el-table-column label="序号" type="index" width="55">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="用户账号"
          prop="userCode"
          width="120"
          sortable
        />
        <el-table-column
          align="center"
          label="用户名称"
          prop="userName"
          width="120"
          sortable
        />
        <el-table-column
          align="center"
          :formatter="formatBingUser"
          label="绑定员工"
          prop="user"
          width="100"
        />
        <el-table-column
          align="center"
          label="用户状态"
          prop="statusDesc"
          width="90"
        />
        <el-table-column
          align="center"
          label="用户类别"
          prop="userTypeDesc"
          width="140"
        />
        <el-table-column
          align="center"
          :formatter="dateFormat"
          label="有效期限"
          prop="validDate"
          width="120"
        />
        <el-table-column
          align="center"
          label="所属部门"
          prop="mainDeptName"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="所属角色"
          prop="roleNames"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="是否可删除"
          prop="ifAllowDelete"
          width="120"
          sortable
        />
        <el-table-column
          align="center"
          label="手机号码"
          prop="phone"
          width="120"
          sortable
        />
        <el-table-column
          align="center"
          label="用户编号"
          prop="labor"
          width="110"
          sortable
        />
        <el-table-column
          align="center"
          :formatter="dateFormat"
          label="创建时间"
          prop="createTime"
          width="120"
          sortable
        />
        <el-table-column align="center" fixed="right" label="操作" width="240">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleDetail(row)"
              >详情</el-button
            >
            <el-button
              v-auth="['sysuser/xg']"
              size="small"
              type="warning"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-auth="['sysuser/czmm']"
              size="small"
              type="danger"
              @click="handleRestPassword(row)"
            >
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="tableOptions.pagination.current"
        :layout="tableOptions.pagination.layout"
        :page-size="tableOptions.pagination.size"
        :total="tableOptions.pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <user-rest-pwd ref="resetPwdRef" width="40%" />
      <user-edit ref="editRef" width="60%" @confirm="handleConfirmEdit" />
    </div>
  </div>
</template>

<script setup name="SysUser">
import { useMessage, useMessageBox } from "@/hooks/message";
import EasyDictSelect from "@/components/dictSelect.vue";
import UserRestPwd from "./components/userRestPwd.vue";
import UserEdit from "./components/userEdit.vue";
import {
  queryUserTable,
  deleteUser,
  lockUser,
  unLockUser
} from "@/api/admin/org/sysuser";
import { dateFormat } from "@/utils/common";
import { getTableHeight } from "@/utils/util";
import { useTable } from "@/hooks/table";

const editRef = ref(null);
const tableRef = ref(null);
const resetPwdRef = ref(null);
const statusRef = ref(null);
const showSearch = ref(true);

const tableOptions = reactive({
  queryForm: {
    userName: "",
    userCode: "",
    status: "ALL"
  },
  queryFunction: queryUserTable,
  descs: ["create_time"]
});

const {
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange
} = useTable(tableOptions, tableRef);

const formatBingUser = row => {
  if (row.user) {
    return row.user.userName;
  } else {
    return "未绑定";
  }
};

onBeforeMount(() => {
  window.addEventListener("resize", handleHeight);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleHeight);
});

onMounted(() => {
  queryTableData();
});

const handleHeight = () => {
  tableOptions.height = getTableHeight(1) - 60 - 30;
};

const handleLock = row => {
  let ids;
  if (row && row.id) {
    ids = row.id;
  } else {
    if (tableOptions.dataSelections.length > 0) {
      ids = tableOptions.dataSelections.map(item => item.id).join();
    } else {
      useMessage().error("未选中任何行");
    }
  }
  useMessageBox()
    .confirm("是否确认锁定选中的用户")
    .then(async () => {
      const { code, msg } = await lockUser({ ids: ids });
      if (code && code === 200) {
        useMessage().success(msg);
        await queryTableData();
      } else {
        useMessage().error(msg);
      }
    });
};

const handleAdd = () => {
  editRef.value.show(null, "add");
};

const handleUnLock = row => {
  let ids;
  if (row && row.id) {
    ids = row.id;
  } else {
    if (tableOptions.dataSelections.length > 0) {
      ids = tableOptions.dataSelections.map(item => item.id).join();
    } else {
      useMessage().error("未选中任何行");
    }
  }
  useMessageBox()
    .confirm("是否确认解除锁定选中的用户")
    .then(async () => {
      const { code, msg } = await unLockUser({ ids: ids });
      if (code && code === 200) {
        useMessage().success(msg);
        await queryTableData();
      } else {
        useMessage().error(msg);
      }
    });
};

const handleDelete = row => {
  let ids;
  if (row && row.id) {
    if (row.ifAllowDelete === "Y") {
      ids = row.id;
    } else {
      useMessage().warning("选中的用户不允许删除");
      return;
    }
  } else {
    if (tableOptions.dataSelections.length > 0) {
      const items = tableOptions.dataSelections.filter(
        item => item.ifAllowDelete === "Y"
      );
      if (items.length > 0) {
        ids = items.map(item => item.id).join();
      } else {
        useMessage().warning("选中的用户均不允许删除");
      }
    } else {
      useMessage().warning("未选中任何行");
    }
  }
  if (ids) {
    useMessageBox()
      .confirm("删除的用户将无法恢复，是否继续")
      .then(async () => {
        const { code, msg } = await deleteUser(ids);
        if (code && code === 200) {
          useMessage().success(msg);
          await queryTableData();
        } else {
          useMessage().warning(msg);
        }
      });
  }
};

const handleRestPassword = row => {
  if (row.id) {
    resetPwdRef.value.show(row);
  } else {
    useMessage().warning("未选中任何行");
  }
};

const handleEdit = row => {
  if (row.id) {
    editRef.value.show(row, "edit");
  } else {
    useMessage().warning("未选中任何行");
  }
};

const handleDetail = row => {
  if (row.id) {
    editRef.value.show(row, "view");
  } else {
    useMessage().warning("未选中任何行");
  }
};

const handleStatusChange = val => {
  tableOptions.queryForm.status = val;
  queryTableData();
};

const handleConfirmEdit = () => {
  queryTableData();
};
</script>

<style lang="scss" scoped></style>
